# -*- coding: utf-8 -*-
"""
@Time : 2024/5/10 2:00 PM
@Author: imamhusan
@Des: 描述
"""
import requests
from fastapi import APIRouter, Response
from core.Response import fail
from core.UyghurCharUtils import UyghurCharUtils
from PIL import Image, ImageDraw, ImageFont, ImageOps
from models.goods import Goods
from models.wx_user import WxUser
import io
import os


router = APIRouter(prefix='/poster')


@router.get('', description='生成海报')
async def poster(xuser: int, goods_id: int = 0):
    try:
        access_token = get_access_token()
        if access_token:
            with Image.open('static/poster.png') as bg_img:
                user = await WxUser.get_or_none(pk=xuser)

                qr_res = generate_qr_code(access_token=access_token, scene=f'{user.pk}&{goods_id}')
                qr_code = Image.open(io.BytesIO(qr_res.content))

                goods = await Goods.get_or_none(pk=goods_id)
                uy_char_util = UyghurCharUtils()
                title = uy_char_util.Basic2RExtend(goods.title_uy)

                goods_image = Image.open(f'static/{goods.image}')
                goods_image = goods_image.resize((480, 520))

                bg_img.paste(qr_code, (90, 1320))
                bg_img.paste(goods_image, (330, 650))

                # 获取draw对象
                draw = ImageDraw.Draw(bg_img)
                font = ImageFont.truetype(font='static/fonts/UKIJQara.ttf', size=36)

                draw.multiline_text((5, 180), text=f'{user.nickName}: {user.pk}', font=font, fill='#40a2ff')
                w, h = bg_img.size
                draw.multiline_text((20, 1200), text=title, font=font, fill='#40a2ff', align='center', max_width=w)

                h_img = requests.get(user.avatarUrl)
                head_imd = Image.open(io.BytesIO(h_img.content))

                # 如果头像要求是圆形，做一个罩子把四角遮住
                size = (128, 128)
                head_imd = head_imd.resize(size)  # 这里要注意设定头像图片大小
                mask = Image.new('L', size, 0)
                draw = ImageDraw.Draw(mask)
                draw.ellipse((0, 0) + size, fill=255)
                head_cover = ImageOps.fit(head_imd, mask.size, centering=(0.5, 0.5))
                head_cover.putalpha(mask)
                # # # 如果要求是方形，head_cover忽略
                bg_img.paste(head_imd, (60, 30), head_cover)  # 将头像贴在背景图上

                buffer = io.BytesIO()
                bg_img.save(buffer, format='png')

                return Response(content=buffer.getvalue(), media_type='image/jpeg')
    except Exception as e:
        return fail(str(e))


def get_access_token():
    url = 'https://api.weixin.qq.com/cgi-bin/token'
    params = {
        "appid": os.getenv('MP_APPID'),
        "secret": os.getenv('MP_SECRET'),
        "grant_type": 'client_credential'
    }
    res = requests.get(url=url, params=params).json()
    return res.get('access_token', None)


def generate_qr_code(access_token: str, page: str = 'pages/index/index', scene: str = 'a=1'):
    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'

    body = {
        "page": page,
        "scene": scene,
        "width": 280,
        # "check_path": False,
        # "env_version": "release"
        # "is_hyaline": True
    }

    res = requests.post(url=url, json=body)

    return res
